/*
 * @Author: jianfanfan 1217572833@qq.com
 * @Date: 2025-03-15 16:06:21
 * @LastEditors: jianfanfan 1217572833@qq.com
 * @LastEditTime: 2025-04-11 15:36:25
 * @FilePath: \guozaoke\src\main.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { LoggerInterceptor } from './common/interceptors/logger.interceptor';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { LoggerService } from './common/logger/logger.service';
import * as fs from 'fs';
import * as path from 'path';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';

async function bootstrap() {
  // 确保日志目录存在
  const logDir = path.join(process.cwd(), 'logs');
  const infoLogDir = path.join(logDir, 'info');
  const errorLogDir = path.join(logDir, 'error');
  const httpLogDir = path.join(logDir, 'http');

  [logDir, infoLogDir, errorLogDir, httpLogDir].forEach((dir) => {
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir, { recursive: true });
    }
  });

  // 创建应用实例
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  // 获取Winston Logger和自定义LoggerService
  const winstonLogger = app.get(WINSTON_MODULE_NEST_PROVIDER);
  const loggerService = app.get(LoggerService);
  loggerService.setContext('Application');

  // 设置应用日志记录器
  app.useLogger(winstonLogger);

  // 全局异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter(loggerService));

  // 全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true,
    }),
  );

  // 全局响应拦截器
  app.useGlobalInterceptors(new TransformInterceptor());

  // 全局日志拦截器
  app.useGlobalInterceptors(new LoggerInterceptor(loggerService));

  // 允许跨域
  app.enableCors();

  // 配置静态资源
  app.useStaticAssets(join(__dirname, '..', 'public'));

  // Swagger配置
  const config = new DocumentBuilder()
    .setTitle('果糟客论坛API')
    .setDescription('果糟客论坛后端API文档')
    .setVersion('1.0')
    .addBearerAuth(
      {
        type: 'http',
        scheme: 'bearer',
        bearerFormat: 'JWT',
        name: 'JWT',
        description: '输入JWT token',
        in: 'header',
      },
      'bearer',
    )
    .addTag('Auth', '用户认证')
    .addTag('Node', '节点管理')
    .addTag('Post', '帖子管理')
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  const port = process.env.PORT || '3000';
  await app.listen(port);
  loggerService.log(`应用程序运行在: http://localhost:${port}`);
  loggerService.log(`Swagger文档地址: http://localhost:${port}/api`);
  loggerService.log(`日志文件存储在: ${logDir}`);
}
bootstrap();
